<?php
/**
 * 题目链接 https://leetcode.cn/problems/remove-element/description/
 */

class Solution {

    /**
     * 轮询 unset
     * @param Integer[] $nums
     * @param Integer $val
     * @return Integer
     */
    public static function removeElement1(array &$nums, int $val): int 
    {
        foreach ($nums as $k => $v) {
            if ($v == $val) {
                unset($nums[$k]);
            }
        }
        
        return count($nums);
    }

    /**
     * 与尾部交换
     * @param Integer[] $nums
     * @param Integer $val
     * @return Integer
     */
    public static function removeElement(array &$nums, int $val): int 
    {
        $len = count($nums);
        for ($i=0; $i < $len;) { 
            if ($nums[$i] == $val) {
                $nums[$i] = $nums[$len - 1];
                $len--;
            } else {
                $i++;
            }
        }

        return $len;
    }
}

$test = [
    [[3,2,2,3], 3],
    [[0,1,2,2,3,0,4,2], 2],
];
$result = [
    2,
    5,
];

foreach ($test as $key => $value) {
    $r = Solution::removeElement($value[0], $value[1]);
    if ($r !== $result[$key]) {
        echo sprintf("第%d个case不通过", $key) . PHP_EOL;
    }
    echo $r . PHP_EOL;
}